from datetime import date, timedelta


from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from rest_framework.views import APIView

from goods.models import GoodsVisitCount
from meiduo_admin.serializers.statistical import GoodsSerializer
from order.models import OrderInfo
from users.models import User



class UserToalCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取用户总数
        now_date = date.today()

        count = User.objects.all().count()

        return Response({
            'count':count,
            'date':now_date
        })

class UserDayCountView(APIView):
    permission_classes = [IsAdminUser]
    def get(self,request):
        # 获取日增用户
        now_date = date.today()

        count = User.objects.filter(date_joined__gte = now_date).count()
        return Response({
            'count':count,
            'date':now_date
        })

class UserActiveCountView(APIView):
    permission_classes = [IsAdminUser]
    def get(self,request):
        # 获取日活跃用户
        now_date = date.today()

        count = User.objects.filter(last_login__gte = now_date).count()
        return Response({
            'count':count,
            'date':now_date
        })

class UserOderCountView(APIView):
    permission_classes = [IsAdminUser]
    def get(self,request):
        # 获取日下单用户
        now_date = date.today()

        # 关联过滤查询
        # count = User.objects.filter(orders_create_time__gte=now_date).count()
        count = OrderInfo.objects.filter(create_time__gte=now_date).count()
        return Response({
            'count': count,
            'date': now_date
        })

class UserMonthCountView(APIView):
    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        now_date = date.today()
        # 获取一个月前日期
        start_date = now_date - timedelta(29)
        # 创建空列表保存每天的用户量
        date_list = []

        for i in range(30):
            # 循环遍历获取当天日期
            index_date = start_date + timedelta(days=i)
            # 指定下一天日期
            cur_date = start_date + timedelta(days=i + 1)
            # 查询条件是大于当前日期index_date，小于明天日期的用户cur_date，得到当天用户量
            count = User.objects.filter(date_joined__gte=index_date, date_joined__lt=cur_date).count()

            date_list.append({
                'count': count,
                'date': index_date
            })

        return Response(date_list)

class GoodsDayView(APIView):
    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取商品分类日访问量
        now_date = date.today()
        goods_days = GoodsVisitCount.objects.filter(date=now_date)
        serializer = GoodsSerializer(goods_days,many=True)


        return Response(serializer.data)